/* Author: DO HOANG HAI
 * Main.java
 *
 * Created on June 4, 2006, 8:55 PM
 *
 * Description: This project demonstrates  how to use Binary search algorithm to search for a value in an one-dimension array 
 *              Requirement: input array must be alrady sorted
 */

package binary;

import java.util.Scanner;

public class Main {
    
    private static int[] array={-30,-21,-6,3,8,11,23,89};
    private static Scanner reader=new Scanner(System.in);
    /** Creates a new instance of Main */
    public Main() {
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        displayOriginalArray();
        System.out.println();
        System.out.println("search for value: ");
        int value=reader.nextInt();
        int result=binarySearch(value, 0, array.length-1);
        if (result==-1) 
            System.out.println(" "+ value+ " is not found! ");
        else System.out.println("index of the element "+value+ " is: "+result);
            
    }
     public static void displayResult(){
         for (int index=0; index<array.length; index++)
            System.out.print("  "+ array[index]);
    }
     public static int binarySearch(int value, int start, int end){
         if (start>end) return -1;
         if (start==end && array[start]!=value) return -1;
         int middle=(end+start)/2;
         if (array[middle]==value) return middle;
         else if (array[middle]<value) return binarySearch(value, middle+1, end);
         else  return binarySearch(value, start, middle-1);
         
     }
     public static void displayOriginalArray(){
        for (int i=0; i<array.length; i++)
        {
            System.out.print("   " + array[i]);    
        }
            
    }
    
}
